while Loop
The structure of a while
loop:
while condition statements % body of while loop end
where condition is the same type of boolean expression that was introduced in the lesson on conditional execution.
The way a while
loop works is as follows:
- The condition expression is evaluated to true or false.
- If the condition evaluates to true,
then the statements in the body of the
while
loop are executed. - After the body of the
while
loop has finished executing, control goes back to the top of thewhile
loop - The condition expression is reevaluated.
- If the condition evaluates to true, the body of the
while
loop is executed, and the condition is evaluated again. - This process repeats until the condition expression evaluates to false.
- If the condition evaluates to false, the statements in the body
of the while loop are skipped and control continues at the next statement after the
while
loop.
As in the if
statement, the while
statement uses
end
to indicate the end of the loop.